package com.youlai.boot.system.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.system.converter.TaskTableV2Converter;
import com.youlai.boot.system.mapper.TaskTableV2Mapper;
import com.youlai.boot.system.model.entity.User;
import com.youlai.boot.system.service.TaskTableV2Service;
import com.youlai.boot.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.system.model.entity.TaskTable;
import com.youlai.boot.system.model.form.TaskTableForm;
import com.youlai.boot.system.model.query.TaskTableQuery;
import com.youlai.boot.system.model.vo.TaskTableVO;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * TaskTable服务实现类
 *
 * @author Gwd
 * @since 2025-03-07 17:09
 */
@Service
@RequiredArgsConstructor
public class TaskTableV2ServiceImpl extends ServiceImpl<TaskTableV2Mapper, TaskTable> implements TaskTableV2Service {

    private final TaskTableV2Converter taskTableConverter;
    private final UserService userService;
    private final TaskTableV2Mapper taskTableV2Mapper;

    /**
     * 获取TaskTable分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<TaskTableVO>} TaskTable分页列表
     */
    @Override
    public IPage<TaskTableVO> getTaskTablePage(TaskTableQuery queryParams) {
        QueryWrapper<TaskTable> queryWrapper = new QueryWrapper<TaskTable>();
        queryWrapper.and(StringUtils.isNotBlank(queryParams.getTaskname()), x->{
            x.like("taskname",queryParams.getTaskname());
        })
                .eq(StringUtils.isNotBlank(queryParams.getTaskpriority()),"taskpriority",queryParams.getTaskpriority())
                .eq(queryParams.getState() != null,"state",queryParams.getState())
        ;
        if(queryParams.getAddtime() != null && queryParams.getAddtime().size() == 2){
            String startTime = queryParams.getAddtime().get(0)+" 00:00:00";
            String endTime = queryParams.getAddtime().get(1)+" 23：59：59";
            queryWrapper.between("addtime",startTime,endTime);
        }
        if(StringUtils.isNotBlank(queryParams.getTaskcharge())){
            queryWrapper.eq(" taskcharge",queryParams.getTaskcharge());
        }
        queryWrapper.orderByDesc("id");
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<TaskTable> page = new Page<TaskTable>(pageNum, pageSize);
        Page<TaskTable> data = this.page(page, queryWrapper);
        if(data != null && data.getTotal() > 0){
            List<TaskTable> records = data.getRecords();
            List<String> collect = records.stream().map(TaskTable::getTaskcharge).distinct().collect(Collectors.toList());
            List<User> userList = userService.list(new QueryWrapper<User>().in("id", collect));
            Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getNickname));
            for (TaskTable record : records) {
                String taskcharge = record.getTaskcharge();
                if(StringUtils.isNotBlank(taskcharge)) {
                    Long tc = Long.parseLong(taskcharge);
                    record.setTaskcharge(userMap.get(tc));
                }
            }

        }
        return taskTableConverter.toPageVO(data);
    }

    /**
     * 获取TaskTable表单数据
     *
     * @param id TaskTableID
     * @return
     */
    @Override
    public TaskTableForm getTaskTableFormData(Long id) {
        TaskTable entity = this.getById(id);
        return taskTableConverter.toForm(entity);
    }

    /**
     * 新增TaskTable
     *
     * @param formData TaskTable表单对象
     * @return
     */
    @Override
    public boolean saveTaskTable(TaskTableForm formData) {
        TaskTable entity = taskTableConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新TaskTable
     *
     * @param id   TaskTableID
     * @param formData TaskTable表单对象
     * @return
     */
    @Override
    public boolean updateTaskTable(Long id,TaskTableForm formData) {
        TaskTable entity = taskTableConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     *
     * 获取首页分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage< TaskTableVO >} 首页分页列表
     */
    @Override
    public IPage<TaskTableVO> getTasktablePage(TaskTableQuery queryParams) {
        Page<TaskTableVO> pageVO = this.baseMapper.getTasktablePage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 删除TaskTable
     *
     * @param ids TaskTableID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteTaskTables(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的TaskTable数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    public int getTotalDoctors() {

        return Math.toIntExact(taskTableV2Mapper.selectCount(null));
    }

    /**
     * 查询所有归档任务
     *
     * @param
     * @return {@link IPage< TaskTableVO >} 首页分页列表
     */
//    @Override
//    public IPage<TaskTableVO> getArchivePage(TaskTableQuery queryParams) {
//        Page<TaskTableVO> pageVO = this.baseMapper.selectTasksByArchiveStatus(
//                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
//                queryParams
//        );
//        return pageVO;
//    }

    @Override
    public TaskTableForm getTasktableFormData(Long id) {
        TaskTable entity = this.getById(id);
        return taskTableConverter.toForm(entity);
    }

    /**
     * 单个归档
     * @param id
     * @param archive
     * @return
     */

    @Override
    public boolean updateArchive(Long id, Integer archive) {
        UpdateWrapper<TaskTable> taskTableUpdateWrapper = new UpdateWrapper<>();
        taskTableUpdateWrapper.eq("id" ,id);
        TaskTable taskTable = new TaskTable();
        taskTable.setArchive(archive);
        return taskTableV2Mapper.update(taskTable,taskTableUpdateWrapper) > 0 ;
    }

    /**
     * 批量归档接口
     * @param id
     * @param archive
     * @return
     */
    @Override
    public boolean batchUpdateArchiveStatus(List<Long> id, Integer archive) {
        if(id == null || id.isEmpty() ) {
            return false;
        }

        UpdateWrapper<TaskTable> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",id);

        TaskTable taskTable = new TaskTable();
        taskTable.setArchive(archive);

        return taskTableV2Mapper.update(taskTable,updateWrapper) >0;
    }
    /**
     * 获取任务完成情况统计数据
     * @return
     */
    @Override
    public List<Map<String, Object>> getTaskCompletionCount() {
        return taskTableV2Mapper.getTaskCompletionCount();
    }


    @Override
    public boolean updateTasktable(Long id, TaskTableForm formData) {
        TaskTable entity = taskTableConverter.toEntity(formData);
        return this.updateById(entity);
    }
    @Override
    public boolean deleteTasktables(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的首页数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
